package framework

import (
	"github.com/gin-gonic/gin"
)

var Gin *gin.Engine

func init() {
	gin.ForceConsoleColor()
	r := gin.Default()
	Gin = r
}

type R struct {
	Data    interface{} `json:"data"`
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Total   int64       `json:"total"`
	Success bool        `json:"success"`
}

type ReqPage struct {
	CurrentPage int `json:"current_page" form:"current_page"`
	Current     int `json:"current" form:"current"`
	PageSize    int `json:"page_size" form:"page_size"`
	Offset      int `json:"-"`
}

type ResPage struct {
	Data  interface{} `json:"data"`
	Total int64       `json:"total"`
}

// result  快速返回
func result(c *gin.Context, code int, message string, data interface{}) {
	r := &R{
		Data:    data,
		Code:    code,
		Msg:     message,
		Success: code == 200,
	}
	c.JSON(200, r)
}

func Ok(c *gin.Context) {
	result(c, 200, "操作成功", nil)
}

func Data(c *gin.Context, data interface{}) {
	result(c, 200, "操作成功", data)
}

func Page(c *gin.Context, data interface{}, total int64) {
	r := &R{
		Data:    data,
		Code:    200,
		Success: true,
		Total:   total,
	}
	c.JSON(200, r)
}

func Fail(c *gin.Context, message string) {
	result(c, 500, message, nil)
}

func Error(c *gin.Context, err error) {
	result(c, 500, err.Error(), nil)
}

func CodeMsg(c *gin.Context, code int, msg string, data interface{}) {
	result(c, code, msg, data)
}

// result  快速返回

func QueryPage(c *gin.Context, page *ReqPage) error {
	err := c.ShouldBind(page)
	if err == nil {
		// 默认第一页
		if page.CurrentPage < 1 {
			page.CurrentPage = 1
		}
		if page.Current < 1 {
			page.Current = 1
		}
		if page.Current > 0 {
			page.CurrentPage = page.Current
		}
		// 默认20
		if page.PageSize < 1 {
			page.PageSize = 20
		}
		page.Offset = (page.CurrentPage - 1) * page.PageSize
	}
	return err
}
